<template>
  <common-header />
  <div class="trade-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <n-flex justify="space-between" align="center">
        <n-h1>器械交易</n-h1>
        <n-text depth="3">这里可以购买新品器械或二手器械</n-text>
      </n-flex>
    </div>

    <!-- 新品器械交易模块 -->
    <div class="trade-section">
      <div class="section-header">
        <n-h2>新品器械交易</n-h2>
      </div>

      <!-- 新品器械列表 -->
      <div class="equipment-grid">
        <n-card
            v-for="item in newEquipments"
            :key="item.id"
            class="equipment-card"
            :bordered="false"
            hoverable
            @click="showEquipmentDetail(item)"
        >
          <n-image
              :src="item.coverImg || '/default_equipment.svg'"
              class="equipment-image"
              preview-disabled
              object-fit="cover"
          />
          <div class="card-content">
            <n-space vertical :size="12">
              <!-- 第一行：商家头像、名称、认证标签 -->
              <n-flex align="center" justify="space-between" style="width: 100%; min-height: 32px;">
                <n-flex align="center" :size="8" style="overflow: hidden; flex: 1; min-width: 0;">
                  <n-avatar
                      round
                      size="small"
                      :src="item.avatarUrl ? BASE_URL + item.avatarUrl : '/default_avatar.svg'"
                      style="flex-shrink: 0;"
                  />
                  <span class="merchant-name">{{ item.merchant }}</span>
                </n-flex>
                <n-tag v-if="item.isVerified" type="success" size="small" class="merchant-tag">
                  认证商家
                </n-tag>
              </n-flex>

              <!-- 第二行：器械名称 -->
              <n-text strong class="equipment-title">{{ item.title }}</n-text>
              <!-- 第三行：价格 -->
              <n-text type="primary" class="price">¥{{ item.price }}</n-text>

              <!-- 库存信息 -->
              <n-text depth="3" v-if="item.quantity > 1">库存: {{ item.quantity }}件</n-text>

              <!-- 点赞和评论信息 -->
              <n-space align="center" :size="12" class="interaction-stats">
                <n-button text @click.stop="handleLike(item)">
                  <template #icon>
                    <n-icon :color="item.isLiked ? '#2080f0' : ''">
                      <ThumbsUp v-if="item.isLiked" />
                      <ThumbsUpOutline v-else />
                    </n-icon>
                  </template>
                  {{ item.likeCount || 0 }}
                </n-button>
                <n-button text @click.stop="showDetailModal(item)">
                  <template #icon>
                    <n-icon><ChatbubbleEllipses /></n-icon>
                  </template>
                  {{ item.commentCount || 0 }}
                </n-button>
              </n-space>
              <!-- 最后一行：根据商品拥有者和认证状态显示不同按钮 -->
              <div class="button-group">
                <!-- 如果是用户自己的商品，显示编辑信息按钮 -->
                <n-button
                    v-if="isCurrentUserItem(item)"
                    type="info"
                    block
                    size="small"
                    @click.stop="handleEditItem(item)"
                >
                  编辑信息
                </n-button>
                <!-- 如果是认证商家的商品，显示立即购买 -->
                <n-button
                    v-else-if="item.isVerified"
                    type="primary"
                    block
                    size="small"
                    @click.stop="handleBuyNow(item)"
                >
                  立即购买
                </n-button>
                <!-- 其他情况显示联系卖家 -->
                <n-button
                    v-else
                    type="primary"
                    block
                    size="small"
                    @click.stop="handleContact(item)"
                >
                  联系卖家
                </n-button>
              </div>
            </n-space>
          </div>
        </n-card>
      </div>
    </div>

    <!-- 二手器械交易模块 -->
    <div class="trade-section">
      <div class="section-header">
        <n-h2>二手器械交易</n-h2>
      </div>

      <!-- 二手器械列表 -->
      <div class="equipment-grid">
        <n-card
            v-for="item in usedEquipments"
            :key="item.id"
            class="equipment-card"
            :bordered="false"
            hoverable
            @click="showEquipmentDetail(item)"
        >
          <n-image
              :src="item.coverImg || '/default_equipment.svg'"
              class="equipment-image"
              preview-disabled
              object-fit="cover"
          />
          <n-tag
              v-if="item.isSold"
              class="sold-tag"
              type="error"
              size="small"
          >已售出</n-tag>
          <div class="card-content">
            <n-space vertical :size="12">
              <!-- 第一行：卖家头像、名称、成色标签 -->
              <n-flex align="center" justify="space-between" style="width: 100%; min-height: 32px;">
                <n-flex align="center" :size="8" style="overflow: hidden; flex: 1; min-width: 0;">
                  <n-avatar
                      round
                      size="small"
                      :src="item.avatarUrl ? BASE_URL + item.avatarUrl : '/default_avatar.svg'"
                      style="flex-shrink: 0;"
                  />
                  <span class="seller-name">卖家: {{ item.seller }}</span>
                </n-flex>
                <n-tag :type="getConditionTag(item.condition)" class="condition-tag">
                  {{ item.condition }}
                </n-tag>
              </n-flex>

              <!-- 第二行：器械名称 -->
              <n-text strong class="equipment-title">{{ item.title }}</n-text>

              <!-- 第三行：价格 -->
              <n-text type="primary" class="price">¥{{ item.price }}</n-text>

              <!-- 库存信息 -->
              <n-text depth="3" v-if="item.quantity > 1">数量: {{ item.quantity }}件</n-text>
              <!-- 最后一行：根据商品拥有者显示不同按钮 -->
              <div class="button-group">
                <!-- 如果是用户自己的商品，显示编辑信息按钮 -->
                <n-button
                    v-if="isCurrentUserItem(item)"
                    type="info"
                    block
                    size="small"
                    :disabled="item.isSold"
                    @click="handleEditItem(item)"
                >编辑信息</n-button>
                <!-- 其他情况显示联系卖家 -->
                <n-button
                    v-else
                    type="primary"
                    block
                    size="small"
                    :disabled="item.isSold"
                    @click="handleContact(item)"
                >联系卖家</n-button>
              </div>
            </n-space>
          </div>
        </n-card>
      </div>
    </div>

    <!-- 器械详情弹窗 -->
    <n-modal
        v-model:show="showDetailModal"
        preset="card"
        style="width: 900px; max-height: 90vh"
        :auto-focus="false"
        :mask-closable="true"
    >
      <n-card :title="detailData?.title || '器械详情'" :bordered="false">
        <template #header-extra>
          <n-button quaternary circle @click="showDetailModal = false">
            <template #icon>
              <n-icon><CloseOutline /></n-icon>
            </template>
          </n-button>
        </template>

        <n-scrollbar style="max-height: 75vh">
          <n-space vertical :size="24" v-if="detailData">
            <!-- 图片展示区域 -->
            <n-card embedded>
              <div class="detail-images">
                <n-carousel
                    ref="carouselRef"
                    v-if="detailData.images && detailData.images.length > 0"
                    effect="card"
                    prev-slide-style="transform: translateX(-150%) translateZ(-800px);"
                    next-slide-style="transform: translateX(50%) translateZ(-800px);"
                    :show-dots="detailData.images.length > 1"
                    :show-arrow="detailData.images.length > 1"
                    :autoplay="true"
                    :interval="4000"
                    :transition-style="{ transitionDuration: '500ms' }"
                    style="height: 400px;"
                    dot-placement="bottom-outside"
                >
                  <n-carousel-item
                      v-for="(image, index) in detailData.images"
                      :key="index"
                      :style="{ width: '80%' }"
                  >
                    <n-image
                        :src="image || '/default_equipment.svg'"
                        object-fit="cover"
                        class="carousel-img"
                        :preview-disabled="false"
                    />
                  </n-carousel-item>
                </n-carousel>
                <n-image
                    v-else
                    src="/default_equipment.svg"
                    object-fit="cover"
                    style="width: 100%; height: 400px; border-radius: 12px;"
                    :preview-disabled="false"
                />

                <!-- 添加右下角切换按钮组 -->
                <div class="carousel-controls" v-if="detailData.images && detailData.images.length > 1">
                  <n-button-group size="small">
                    <n-button @click="prevSlide" secondary circle>
                      <template #icon>
                        <n-icon><ChevronBack /></n-icon>
                      </template>
                    </n-button>
                    <n-button @click="nextSlide" secondary circle>
                      <template #icon>
                        <n-icon><ChevronForward /></n-icon>
                      </template>
                    </n-button>
                  </n-button-group>
                </div>
              </div>
            </n-card>

            <!-- 器械基本信息 -->
            <n-grid cols="1 s:2" :x-gap="24" :y-gap="16">
              <!-- 左侧：器械信息 -->
              <n-grid-item>
                <n-card title="器械信息" size="small" embedded>
                  <n-space vertical :size="16">
                    <!-- 器械名称 -->
                    <div>
                      <n-text depth="3" style="font-size: 14px;">器械名称</n-text>
                      <n-h3 style="margin: 4px 0; color: #333;">{{ detailData.title }}</n-h3>
                    </div>

                    <!-- 价格 -->
                    <div>
                      <n-text depth="3" style="font-size: 14px;">价格</n-text>
                      <n-h2 type="primary" style="margin: 4px 0; color: #18a058;">
                        ¥{{ detailData.price }}
                      </n-h2>
                    </div>

                    <!-- 器械属性 -->
                    <n-space vertical :size="8">
                      <n-flex justify="space-between" align="center">
                        <n-text depth="3">器械类型</n-text>
                        <n-tag :type="detailData.equipmentType === 'NEW' ? 'success' : 'info'" round>
                          {{ detailData.equipmentType === 'NEW' ? '新品器械' : '二手器械' }}
                        </n-tag>
                      </n-flex>

                      <n-flex v-if="detailData.equipmentType === 'USED'" justify="space-between" align="center">
                        <n-text depth="3">成色等级</n-text>
                        <n-tag :type="getConditionTag(detailData.condition)" round>
                          {{ detailData.condition }}
                        </n-tag>
                      </n-flex>

                      <n-flex v-if="detailData.quantity > 1" justify="space-between" align="center">
                        <n-text depth="3">数量</n-text>
                        <n-text strong>{{ detailData.quantity }} 件</n-text>
                      </n-flex>
                    </n-space>
                  </n-space>
                </n-card>
              </n-grid-item>

              <!-- 右侧：卖家信息 -->
              <n-grid-item>
                <n-card :title="detailData.equipmentType === 'NEW' ? '商家信息' : '卖家信息'" size="small" embedded>
                  <n-space vertical :size="16">
                    <n-flex align="center" :size="16">
                      <n-avatar
                          round
                          size="large"
                          :src="detailData.avatarUrl ? BASE_URL + detailData.avatarUrl : '/default_avatar.svg'"
                      />
                      <n-space vertical :size="4">
                        <n-text strong style="font-size: 16px;">
                          {{ detailData.equipmentType === 'NEW' ? detailData.merchant : detailData.seller }}
                        </n-text>
                        <n-space :size="8">
                          <n-tag v-if="detailData.isVerified" type="success" size="small" round>
                            <template #icon>
                              <n-icon><CheckmarkCircle /></n-icon>
                            </template>
                            认证商家
                          </n-tag>
                        </n-space>
                      </n-space>
                    </n-flex>

                    <!-- 联系方式提示 - 只在非认证商家时显示 -->
                    <n-alert
                        v-if="!detailData.isVerified"
                        type="info"
                        size="small"
                        :show-icon="false"
                    >
                      <template #icon>
                        <n-icon><InformationCircle /></n-icon>
                      </template>
                      点击下方按钮可以与{{ detailData.equipmentType === 'NEW' ? '商家' : '卖家' }}取得联系
                    </n-alert>
                  </n-space>
                </n-card>
              </n-grid-item>
            </n-grid>            <!-- 器械描述 -->
            <n-card title="器械描述" size="small" embedded>
              <n-text style="line-height: 1.6; white-space: pre-wrap;">
                {{ detailData.description || '暂无详细描述信息' }}
              </n-text>
            </n-card>

            <!-- 点赞区域 -->
            <n-card title="点赞支持" size="small" embedded>
              <n-space align="center" :size="16">
                <n-button
                    @click="handleDetailLike"
                    :type="detailLikeData.isLiked ? 'primary' : 'default'"
                    round
                    size="large"
                >
                  <template #icon>
                    <n-icon>
                      <ThumbsUp v-if="detailLikeData.isLiked" />
                      <ThumbsUpOutline v-else />
                    </n-icon>
                  </template>
                  {{ detailLikeData.isLiked ? '已点赞' : '点赞' }}
                </n-button>
                <n-text strong>{{ detailLikeData.count }} 人点赞</n-text>
              </n-space>
            </n-card>

            <!-- 评论区 -->
            <n-card title="商品评论" size="small" embedded>
              <n-space vertical :size="16">
                <!-- 评论计数 -->
                <n-flex justify="space-between" align="center">
                  <n-text strong>评论</n-text>
                  <n-tag :bordered="false" size="small" type="info">{{ currentCommentCount || 0 }}</n-tag>
                </n-flex>

                <!-- 评论输入框 -->
                <n-input
                    v-model:value="newComment"
                    type="textarea"
                    placeholder="写下你对这个商品的评论..."
                    :autosize="{ minRows: 2, maxRows: 4 }"
                />
                <n-button
                    block
                    type="primary"
                    @click="handleSendComment"
                    :disabled="!newComment.trim()"
                >
                  发送评论
                </n-button>

                <!-- 评论列表 -->
                <template v-if="currentComments?.length">
                  <n-thing
                      v-for="comment in currentComments"
                      :key="comment.commentId"
                      class="comment-item"
                  >
                    <template #avatar>
                      <n-avatar
                          :src="comment.avatarImgUrl ? BASE_URL + comment.avatarImgUrl : '/default_avatar.svg'"
                          round
                          :size="40"
                          fallback-src="/default_avatar.svg"
                      />
                    </template>
                    <template #header>
                      <n-space align="center" :size="8">
                        <n-text strong>{{ comment.nickname || comment.userNickname || '匿名用户' }}</n-text>
                        <n-text depth="3" size="tiny">{{ comment.createTime }}</n-text>
                      </n-space>
                    </template>
                    <template #description>
                      <n-text depth="2">{{ comment.content }}</n-text>
                    </template>
                  </n-thing>
                </template>
                <template v-else>
                  <n-empty description="暂无评论，快来抢沙发吧~" />
                </template>
              </n-space>
            </n-card>

            <!-- 操作按钮 -->
            <n-card embedded>
              <n-space justify="center" :size="16">
                <n-button size="large" @click="showDetailModal = false">
                  <template #icon>
                    <n-icon><CloseOutline /></n-icon>
                  </template>
                  关闭
                </n-button>
                <n-button
                    v-if="detailData.isVerified"
                    type="primary"
                    size="large"
                    :disabled="detailData.isSold"
                    @click.stop="handleBuyNow(detailData)"
                >
                  <template #icon>
                    <n-icon><CartOutline /></n-icon>
                  </template>
                  {{ detailData.isSold ? '已售出' : '立即购买' }}
                </n-button>
                <n-button
                    v-else
                    type="primary"
                    size="large"
                    :disabled="detailData.isSold"
                    @click.stop="handleContact(detailData)"
                >
                  <template #icon>
                    <n-icon><ChatbubbleEllipses /></n-icon>
                  </template>
                  {{ detailData.isSold ? '已售出' : '联系卖家' }}
                </n-button>
              </n-space>
            </n-card>
          </n-space>
        </n-scrollbar>
      </n-card>    </n-modal>

    <!-- 支付弹窗 -->
    <n-modal
        v-model:show="showPaymentModal"
        preset="card"
        style="width: 500px;"
        title="确认购买"
        :auto-focus="false"
        :mask-closable="false"
    >
      <n-space vertical :size="20" v-if="paymentData">
        <!-- 商品信息 -->
        <n-card embedded>
          <n-space vertical :size="12">
            <n-flex align="center" :size="12">
              <n-image
                  :src="paymentData.coverImg || '/default_equipment.svg'"
                  width="80"
                  height="80"
                  object-fit="cover"
                  preview-disabled
                  style="border-radius: 8px;"
              />
              <n-space vertical :size="4" style="flex: 1;">
                <n-text strong>{{ paymentData.title }}</n-text>
                <n-text type="primary" style="font-size: 18px; font-weight: bold;">
                  ¥{{ paymentData.price }}
                </n-text>
              </n-space>
            </n-flex>
            <!-- 购买数量选择 -->
            <n-flex justify="space-between" align="center">
              <n-text>购买数量:</n-text>              <n-input-number
                v-model:value="paymentData.quantity"
                :min="1"
                :max="999"
                style="width: 120px;"
                @update:value="updateQuantityAndQRCode"
            />
            </n-flex>

            <!-- 总金额 -->
            <n-flex justify="space-between" align="center">
              <n-text strong>总金额:</n-text>
              <n-text type="primary" style="font-size: 20px; font-weight: bold;">
                ¥{{ paymentData.totalAmount }}
              </n-text>
            </n-flex>
          </n-space>
        </n-card>

        <!-- 支付方式 -->
        <n-card title="支付方式" embedded>
          <n-space vertical :size="16">
            <!-- 商家二维码 -->
            <div v-if="paymentData.qrCodeUrl" style="text-align: center;">
              <n-text depth="2" style="display: block; margin-bottom: 12px;">
                请使用微信/支付宝扫码支付
              </n-text>
              <n-image
                  :src="BASE_URL + paymentData.qrCodeUrl"
                  width="200"
                  height="200"
                  object-fit="contain"
                  :preview-disabled="false"
                  style="border: 1px solid #f0f0f0; border-radius: 8px;"
              />
            </div>

            <!-- 无二维码提示 -->
            <n-alert v-else type="warning" :show-icon="false">
              该商家暂未设置收款二维码，请联系商家获取付款方式
            </n-alert>

            <!-- 支付说明 -->
            <n-alert type="info" :show-icon="false">
              <template #icon>
                <n-icon><InformationCircle /></n-icon>
              </template>
              扫码支付完成后，请点击"我已完成支付"按钮，系统将自动创建订单并为您开启与商家的聊天会话
            </n-alert>
          </n-space>
        </n-card>
      </n-space>

      <template #action>
        <n-space>
          <n-button @click="showPaymentModal = false">取消</n-button>
          <n-button
              type="primary"
              @click="confirmPayment"
              :disabled="!paymentData?.qrCodeUrl"
          >
            我已完成支付
          </n-button>
        </n-space>
      </template>    </n-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { useRouter } from 'vue-router'
import CommonHeader from '../../components/CommonHeader.vue'
import http from '../../utils/http.js'
import {
  CloseOutline,
  CheckmarkCircle,
  InformationCircle,
  CartOutline,
  ChatbubbleEllipses,
  ChevronBack,
  ChevronForward,
  ThumbsUp,
  ThumbsUpOutline
} from '@vicons/ionicons5'

const message = useMessage()
const router = useRouter()
const BASE_URL = window.BASE_URL

// 获取用户信息的工具函数
function getUser() {
  const userStr = localStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
}

// 获取评论列表
const fetchComments = async (tradeId) => {
  try {
    const response = await http.get(`/api/comments/target/${tradeId}/2`); // 商品类型为2

    if (response.data.code === 2000) {
      currentComments.value = response.data.data || [];
      currentCommentCount.value = currentComments.value.length;
    } else {
      console.error('获取评论失败:', response.data.msg);
      currentComments.value = [];
      currentCommentCount.value = 0;
    }
  } catch (error) {
    console.error('获取评论失败:', error);
    currentComments.value = [];
    currentCommentCount.value = 0;
  }
}

// 发送评论
const handleSendComment = async () => {
  if (!newComment.value.trim()) {
    message.warning('请输入评论内容');
    return;
  }

  const user = getUser();
  if (!user) {
    message.warning('请先登录');
    return;
  }

  try {
    const response = await http.post('/api/comments', {
      targetId: detailData.value.id,
      targetType: 2, // 商品类型为2
      content: newComment.value.trim(),
      userId: user.userId
    });

    if (response.data.code === 2000) {
      message.success('评论成功');
      newComment.value = '';
      // 重新获取评论列表
      await fetchComments(detailData.value.id);
    } else {
      message.error(response.data.msg || '评论失败');
    }  } catch (error) {
    console.error('评论失败:', error);
    message.error('评论失败，请稍后重试');
  }
}

// 获取点赞信息
const fetchLikeInfo = async (targetId, targetType) => {
  try {
    const response = await http.get('/v1/like/info', {
      params: {
        targetId: targetId,
        targetType: targetType
      }
    });

    if (response.data.code === 2000) {
      detailLikeData.value = {
        isLiked: response.data.data.isLiked || false,
        count: response.data.data.count || 0
      };
    } else {
      console.error('获取点赞信息失败:', response.data.msg);
      detailLikeData.value = { isLiked: false, count: 0 };
    }
  } catch (error) {
    console.error('获取点赞信息失败:', error);
    detailLikeData.value = { isLiked: false, count: 0 };
  }
}

// 处理卡片中的点赞
const handleLike = async (item) => {
  const user = getUser();
  if (!user) {
    message.warning('请先登录');
    return;
  }

  try {
    const response = await http.post('/v1/like/toggle', {
      targetId: item.id,
      targetType: 2 // 交易商品类型为2
    });
    if (response.data.code === 2000) {
      const likeData = response.data.data;

      // 更新列表中的点赞状态
      item.isLiked = likeData.isLiked;
      item.likeCount = likeData.likeCount;

      message.success(likeData.isLiked ? '点赞成功' : '取消点赞');
    } else {
      message.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    message.error('操作失败，请稍后重试');
  }
}

// 处理详情页面的点赞
const handleDetailLike = async () => {
  const user = getUser();
  if (!user) {
    message.warning('请先登录');
    return;
  }

  try {
    const response = await http.post('/v1/like/toggle', {
      targetId: detailData.value.id,
      targetType: 2 // 交易商品类型为2
    });

    if (response.data.code === 2000) {
      const likeData = response.data.data;
      // 更新详情页点赞状态
      detailLikeData.value = {
        isLiked: likeData.isLiked,
        count: likeData.likeCount
      };

      // 同时更新列表中对应项的点赞状态
      const updateItemInList = (list) => {
        const item = list.find(item => item.id === detailData.value.id);
        if (item) {
          item.isLiked = likeData.isLiked;
          item.likeCount = likeData.likeCount;
        }
      };

      updateItemInList(newEquipments.value);
      updateItemInList(usedEquipments.value);

      message.success(likeData.isLiked ? '点赞成功' : '取消点赞');
    } else {
      message.error(response.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    message.error('操作失败，请稍后重试');
  }
}

// 判断是否为当前用户的商品
const isCurrentUserItem = (item) => {
  const user = getUser();
  return user && user.userId === item.userId;
}

// 编辑商品信息 - 跳转到个人中心的上架管理
const handleEditItem = (item) => {
  router.push({
    path: '/user/center',
    query: {
      tab: 'my-trades', // 跳转到上架器械管理选项卡
      edit: item.id // 传递商品ID，用于定位到具体商品
    }
  });
}

// 新品器械和二手器械数据
const newEquipments = ref([])
const usedEquipments = ref([])

// 详情弹窗相关数据
const showDetailModal = ref(false)
const detailData = ref(null)

// 支付弹窗相关数据
const showPaymentModal = ref(false)
const paymentData = ref(null)

// 评论相关数据
const newComment = ref('')
const currentComments = ref([])
const currentCommentCount = ref(0)

// 点赞相关数据
const detailLikeData = ref({
  isLiked: false,
  count: 0
})

// 获取所有交易数据
const fetchTradeData = async () => {
  try {
    const response = await http.get('/v1/trade/select')
    if (response.data.code === 2000) {
      const tradeList = response.data.data

      // 输出交易数据结构，便于调试
      console.log('获取到的交易数据第一项:', tradeList.length > 0 ? tradeList[0] : '无数据')

      // 为每个交易项获取对应的用户/商家信息
      const tradeListWithUserInfo = await Promise.all(
          tradeList.map(async (item) => {
            try {
              // 使用 selectByUserId 接口获取用户信息
              const userResponse = await http.get('/v1/user/selectByUserId', {
                params: { userId: item.userId }
              })

              if (userResponse.data.code === 2000) {
                return {
                  ...item,
                  userInfo: userResponse.data.data // 保存用户信息
                }
              } else {
                console.warn(`获取用户${item.userId}信息失败:`, userResponse.data.msg)
                return item
              }
            } catch (error) {
              console.error(`获取用户${item.userId}信息出错:`, error)
              return item
            }
          })
      )

      // 处理二手器械数据
      usedEquipments.value = tradeListWithUserInfo
          .filter(item => item.equipmentType === 'USED') // 器械类型为USED的为二手
          .map(item => {
            // 使用conditionLevel字段作为成色信息
            const condition = item.conditionLevel || getRandomCondition()

            // 获取用户昵称和头像
            let sellerName = '匿名用户'
            let avatarUrl = null

            if (item.userInfo) {
              sellerName = item.userInfo.nickname || item.userInfo.username || '匿名用户'
              avatarUrl = item.userInfo.avatarImgUrl
            }

            console.log(`处理用户${item.userId}信息:`, {
              userInfo: item.userInfo,
              nickname: item.userInfo?.nickname,
              username: item.userInfo?.username,
              finalSellerName: sellerName
            })
            return {
              id: item.tradeId,
              title: item.equipmentName,
              coverImg: item.images && item.images.length > 0 ? item.images[0] : null,
              price: item.price,
              seller: sellerName,
              avatarUrl: avatarUrl, // 添加头像URL
              condition: condition,
              isSold: item.status === 'UNAVAILABLE',
              description: item.description,
              quantity: item.quantity,
              images: item.images || [],              userId: item.userId,
              equipmentType: item.equipmentType, // 确保传递器械类型
              isLiked: false, // 初始化点赞状态
              likeCount: 0, // 初始化点赞数量
              commentCount: 0 // 初始化评论数量
            }
          })
          .sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0)) // 按点赞数降序排序

      // 处理新品器械数据
      newEquipments.value = tradeListWithUserInfo
          .filter(item => item.equipmentType === 'NEW') // 器械类型为NEW的为新品
          .map(item => {
            // 如果有用户信息并且是商家角色，显示商家名称
            let merchantName = '用户'
            let avatarUrl = null
            let isVerified = false // 默认不认证

            if (item.userInfo) {
              // 获取头像URL
              avatarUrl = item.userInfo.avatarImgUrl

              // 如果是商家角色(role=3)，才显示认证商家
              if (item.userInfo.role === 3) {
                isVerified = true
                if (item.userInfo.merchantInfo) {
                  merchantName = item.userInfo.merchantInfo.name || '认证商家'
                } else {
                  merchantName = '认证商家'
                }
              } else {
                // 非商家角色显示用户昵称或用户名
                merchantName = item.userInfo.nickname || item.userInfo.username || '用户'
              }
            }

            console.log(`处理商家${item.userId}信息:`, {
              userInfo: item.userInfo,
              role: item.userInfo?.role,
              nickname: item.userInfo?.nickname,
              username: item.userInfo?.username,
              finalMerchantName: merchantName,
              isVerified: isVerified
            })
            return {
              id: item.tradeId,
              title: item.equipmentName,
              coverImg: item.images && item.images.length > 0 ? item.images[0] : null,
              price: item.price,
              merchant: merchantName,
              avatarUrl: avatarUrl, // 添加头像URL
              rating: 4.8,
              isVerified: isVerified, // 只有商家角色才认证
              description: item.description,
              quantity: item.quantity,
              images: item.images || [],              userId: item.userId,
              equipmentType: item.equipmentType, // 确保传递器械类型
              isLiked: false, // 初始化点赞状态
              likeCount: 0, // 初始化点赞数量
              commentCount: 0 // 初始化评论数量
            }
          })
          .sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0)) // 按点赞数降序排序

      console.log('获取交易数据成功（已按点赞数排序）:', { newEquipments: newEquipments.value, usedEquipments: usedEquipments.value })
    } else {
      message.error(response.data.msg || '获取交易数据失败')
    }
  } catch (error) {
    console.error('获取交易数据失败:', error)
    message.error('获取交易数据失败，请稍后重试')
  }
}

const getConditionTag = (condition) => {
  if (condition.includes('全新') || condition.includes('9')) return 'success'
  if (condition.includes('八') || condition.includes('8')) return 'info'
  if (condition.includes('七') || condition.includes('7')) return 'warning'
  if (condition.includes('六') || condition.includes('6')) return 'error'
  return 'default'
}

// 生成随机成色
const getRandomCondition = () => {
  const conditions = ['9成新', '8成新', '7成新', '6成新']
  return conditions[Math.floor(Math.random() * conditions.length)]
}

const handleBuyNow = async (item) => {
  // 检查用户是否登录
  const user = getUser();
  if (!user?.tokenInfo?.isLogin) {
    message.warning('请先登录后再购买');
    router.push('/login');
    return;
  }

  console.log('开始购买流程:', item);
  console.log('当前用户:', user);

  try {
    // 1. 检查用户是否设置了地址
    console.log('检查用户地址...');
    const addressCheckResponse = await http.get('/v1/order/check-address');
    console.log('地址检查结果:', addressCheckResponse);

    if (addressCheckResponse.data.code === 2000) {
      if (!addressCheckResponse.data.data) {
        // 用户未设置地址，跳转到个人中心
        message.warning('请先在个人中心设置您的地址信息');
        router.push('/user/center');
        return;
      }
    } else {
      message.error('检查地址信息失败: ' + (addressCheckResponse.data.msg || '未知错误'));
      return;
    }

    // 2. 生成包含订单信息的动态QR码
    console.log('生成订单二维码...');
    const totalAmount = (item.price * 1).toFixed(2); // 默认数量为1
    const qrCodeResponse = await http.get('/v1/merchant/generateOrderQRCode', {
      params: {
        userId: item.userId,
        equipmentName: item.title,
        quantity: 1,
        totalAmount: totalAmount
      }
    });

    console.log('二维码生成结果:', qrCodeResponse);

    let qrCodeUrl = null;
    if (qrCodeResponse.data.code === 2000) {
      qrCodeUrl = qrCodeResponse.data.data;
      console.log('生成动态订单QR码成功:', qrCodeUrl);
    } else {
      console.error('生成订单QR码失败:', qrCodeResponse.data);
      message.error('生成付款二维码失败: ' + (qrCodeResponse.data.msg || '未知错误'));
      return;
    }

    // 3. 显示支付弹窗
    console.log('显示支付弹窗...');
    showPaymentModalHandler(item, qrCodeUrl);

  } catch (error) {
    console.error('购买流程出错:', error);
    message.error('购买失败，请稍后重试: ' + (error.message || '未知错误'));
  }
}

// 显示支付弹窗
const showPaymentModalHandler = (item, qrCodeUrl) => {
  paymentData.value = {
    ...item,
    qrCodeUrl: qrCodeUrl,
    quantity: 1, // 默认购买数量
    totalAmount: item.price
  };
  showPaymentModal.value = true;
  console.log('支付数据:', paymentData.value);
}

// 当购买数量改变时重新生成QR码
const updateQuantityAndQRCode = async (newQuantity) => {
  if (!paymentData.value || newQuantity <= 0) return;

  paymentData.value.quantity = newQuantity;
  paymentData.value.totalAmount = (paymentData.value.price * newQuantity).toFixed(2);

  try {
    // 重新生成包含新数量和总金额的动态QR码
    const qrCodeResponse = await http.get('/v1/merchant/generateOrderQRCode', {
      params: {
        userId: paymentData.value.userId,
        equipmentName: paymentData.value.title,
        quantity: newQuantity,
        totalAmount: paymentData.value.totalAmount
      }
    });

    if (qrCodeResponse.data.code === 2000) {
      paymentData.value.qrCodeUrl = qrCodeResponse.data.data;
      console.log('重新生成动态订单QR码:', paymentData.value.qrCodeUrl);
    } else {
      console.error('重新生成订单QR码失败:', qrCodeResponse.data);
      message.error('更新付款二维码失败');
    }
  } catch (error) {
    console.error('更新QR码失败:', error);
    message.error('更新付款二维码失败');
  }
}

// 确认支付后创建订单
const confirmPayment = async () => {
  try {
    console.log('确认支付，创建订单:', paymentData.value);

    const user = getUser();
    if (!user?.tokenInfo?.isLogin) {
      message.warning('请先登录');
      return;
    }
    // 创建订单参数
    const orderCreateParam = {
      tradeId: paymentData.value.id, // 使用商品的ID作为tradeId
      sellerId: paymentData.value.userId, // 卖家ID
      equipmentName: paymentData.value.title,
      quantity: paymentData.value.quantity,
      price: paymentData.value.price,
      buyerAddress: null // 后端会自动获取用户地址
    };

    console.log('订单创建参数:', orderCreateParam);
    console.log('用户信息:', user);

    // 调用创建订单接口
    console.log('调用创建订单API...');
    const response = await http.post('/v1/order/create', orderCreateParam);
    console.log('订单创建响应:', response);    if (response.data.code === 2000) {
      message.success('订单创建成功！已自动为您创建与商家的聊天会话');
      console.log('订单创建成功，订单数据:', response.data.data);

      // 关闭支付弹窗和详情弹窗
      showPaymentModal.value = false;
      showDetailModal.value = false;

      // 跳转到聊天页面
      setTimeout(() => {
        router.push({
          path: '/chat',
          query: {
            sellerId: paymentData.value.userId,
            sellerName: paymentData.value.merchant || paymentData.value.seller || '商家',
            sellerAvatar: paymentData.value.avatarUrl
          }
        });
      }, 1000);

    } else {
      console.error('订单创建失败:', response.data);
      message.error(response.data.msg || '订单创建失败');
    }

  } catch (error) {
    console.error('创建订单失败:', error);
    message.error('订单创建失败，请稍后重试: ' + (error.response?.data?.msg || error.message || '未知错误'));
  }
}

const handleContact = async (item) => {
  // 检查用户是否登录
  const user = getUser();
  if (!user?.tokenInfo?.isLogin) {
    message.warning('请先登录后再联系卖家');
    router.push('/login');
    return;
  }
  try {
    // 获取卖家/商家的名称和头像信息
    const sellerName = item.seller || item.merchant || '用户';
    const sellerId = item.sellerId || item.userId;

    // 创建或获取与卖家的聊天会话
    const response = await http.post('/v1/chat/create', {
      sellerId: sellerId,
      sellerName: sellerName,
      equipmentId: item.id,
      equipmentTitle: item.title
    });

    if (response.data.code === 2000) {
      // 跳转到聊天页面，并传递聊天会话ID和卖家信息
      router.push({
        path: '/chat',
        query: {
          sessionId: response.data.data.sessionId || response.data.data.id,
          sellerId: sellerId,
          sellerName: sellerName,
          sellerAvatar: item.avatarUrl
        }
      });
    } else {
      message.error(response.data.msg || '创建聊天会话失败');
    }
  } catch (error) {
    console.error('联系卖家失败:', error);
    message.error('联系卖家失败，请稍后重试');
  }
}

// 显示器械详情
const showEquipmentDetail = async (item, event) => {
  // 阻止事件冒泡，防止卡片点击事件冲突
  if (event) {
    event.stopPropagation()
  }

  console.log('点击的器械详情:', item)
  console.log('器械类型:', item.equipmentType)
  console.log('卖家信息:', item.seller)
  console.log('商家信息:', item.merchant)

  // 处理图片数据，确保是完整的URL
  const processedItem = {
    ...item,
    images: item.images && item.images.length > 0
        ? item.images.map(img => img.startsWith('http') ? img : BASE_URL + img)
        : [],
    // 确保equipmentType正确传递
    equipmentType: item.equipmentType || (item.isVerified ? 'NEW' : 'USED'),
    condition: item.condition || '九成新'
  }

  console.log('处理后的详情数据:', processedItem)
  detailData.value = processedItem
  showDetailModal.value = true

  // 获取该商品的评论
  await fetchComments(item.id)

  // 获取该商品的点赞信息
  await fetchLikeInfo(item.id, 2) // targetType 2 表示交易商品
}

// 轮播图引用和控制方法
const carouselRef = ref(null)

// 切换到上一张图片
const prevSlide = () => {
  if (carouselRef.value) {
    carouselRef.value.prev()
  }
}

// 切换到下一张图片
const nextSlide = () => {
  if (carouselRef.value) {
    carouselRef.value.next()
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchTradeData()
})
</script>

<style scoped>
.trade-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.action-bar {
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.trade-section {
  margin-bottom: 40px;
}

.section-header {
  margin-bottom: 20px;
}

.equipment-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.equipment-card {
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  border-radius: 12px;
  min-height: 400px;
}

.equipment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.equipment-image {
  width: 100%;
  height: 240px;
  object-fit: cover;
  border-radius: 12px 12px 0 0;
}

/* 添加器械标题样式 */
.equipment-title {
  font-size: 16px;
  line-height: 1.4;
  margin: 8px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 44px;
}

/* 调整间距，使整体更紧凑 */
.card-content {
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 160px;
}

/* 价格样式微调 */
.price {
  font-size: 20px;
  font-weight: bold;
  margin: 8px 0;
  color: #18a058;
}

.button-group {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.condition-tag {
  font-weight: bold;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.sold-tag {
  position: absolute;
  top: 12px;
  right: 12px;
}

/* 商家和卖家名称样式 */
.merchant-name, .seller-name {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  flex: 1;
  min-width: 0;
  font-size: 14px;
  color: #666;
}

/* 标签样式调整，确保不会换行 */
.merchant-tag, .condition-tag {
  flex-shrink: 0; /* 防止标签被压缩 */
  white-space: nowrap; /* 防止标签内文字换行 */
  margin-left: 8px; /* 与名称保持一定距离 */
}

/* 评论区域样式 */
.comment-section {
  margin-top: 24px;
}

.comment-item {
  padding: 16px;
  border-radius: 8px;
  background: #fafafa;
  margin-bottom: 12px;
  transition: background-color 0.2s ease;
}

.comment-item:hover {
  background: #f0f0f0;
}

.comment-item:last-child {
  margin-bottom: 0;
}

/* 确保评论输入框样式一致 */
:deep(.n-input) {
  border-radius: 8px;
}

:deep(.n-input:focus-within) {
  border-color: #18a058;
  box-shadow: 0 0 0 2px rgba(24, 160, 88, 0.2);
}

/* 移除原有样式，避免冲突 */
.merchant-info, .seller-info {
  display: none;
}

/* 确保文本省略在多行文本上也能正常工作 */
:deep(.n-ellipsis) {
  max-width: 100%;
}

/* 器械卡片图片容器优化 */
:deep(.equipment-card .n-card__content) {
  padding: 0 !important;
}

:deep(.equipment-card .n-image) {
  display: block;
  width: 100%;
  border-radius: 12px 12px 0 0;
}

:deep(.equipment-card .n-image img) {
  width: 100%;
  height: 240px;
  object-fit: cover;
  object-position: center;
  transition: transform 0.3s ease;
}

:deep(.equipment-card:hover .n-image img) {
  transform: scale(1.05);
}

/* 器械详情弹窗样式 */
.detail-images {
  width: 100%;
  position: relative;
}

/* 轮播图样式优化 */
:deep(.n-carousel) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.n-carousel .n-carousel__slides) {
  height: 400px;
}

:deep(.n-carousel .n-carousel__dots) {
  bottom: -40px;
  gap: 8px;
}

:deep(.n-carousel .n-carousel__dot) {
  background-color: rgba(255, 255, 255, 0.6);
  border: 2px solid rgba(255, 255, 255, 0.8);
  width: 12px;
  height: 12px;
}

:deep(.n-carousel .n-carousel__dot--active) {
  background-color: #18a058;
  border-color: #18a058;
}

:deep(.n-carousel .n-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 40px;
  height: 40px;
  backdrop-filter: blur(4px);
}

:deep(.n-carousel .n-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.8);
  transform: scale(1.1);
}

:deep(.n-carousel .n-carousel__arrow .n-icon) {
  color: white;
  font-size: 18px;
}

/* 卡片轮播图片样式 */
.carousel-img {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 12px;
}

/* 卡片样式优化 */
:deep(.n-card.n-card--embedded) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

:deep(.n-card.n-card--embedded:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

/* 按钮样式优化 */
:deep(.n-button--primary) {
  background: linear-gradient(135deg, #18a058, #36ad6a);
  border: none;
  box-shadow: 0 4px 12px rgba(24, 160, 88, 0.3);
  transition: all 0.3s ease;
}

:deep(.n-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(24, 160, 88, 0.4);
}

:deep(.n-button--primary:disabled) {
  background: #f5f5f5;
  color: #c2c2c2;
  box-shadow: none;
  transform: none;
}

/* 标签样式优化 */
:deep(.n-tag) {
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 轮播图控制按钮组样式 */
.carousel-controls {
  position: absolute;
  right: 24px;
  bottom: 24px;
  z-index: 100;
  display: flex;
  gap: 8px;
}

.carousel-controls .n-button {
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.2s ease;
}

.carousel-controls .n-button:hover {
  background-color: rgba(255, 255, 255, 0.9);
  transform: scale(1.1);
}

/* 确保轮播图容器是相对定位，使得控制按钮可以绝对定位 */
.detail-images {
  width: 100%;
  position: relative;
}

/* 订单状态区域样式 */
.order-status-section {
  margin-top: 40px;
  position: sticky;
  bottom: 20px;
  z-index: 10;
}

.order-status-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.recent-orders {
  max-height: 200px;
  overflow-y: auto;
}

.order-item {
  padding: 12px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid var(--primary-color);
}

.order-item:hover {
  background: #f0f0f0;
  transition: background-color 0.2s ease;
}

/* 响应式布局优化 */
@media (max-width: 1024px) {
  .equipment-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
  }

  .equipment-card {
    min-height: 380px;
  }

  .equipment-image {
    height: 220px;
  }
}

@media (max-width: 768px) {
  .equipment-grid {
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 16px;
  }

  .equipment-card {
    min-height: 360px;
  }

  .equipment-image {
    height: 200px;
  }

  .card-content {
    padding: 14px 16px;
    min-height: 140px;
  }

  :deep(.n-modal) {
    width: 95vw !important;
    margin: 0 auto;
  }

  .detail-images {
    height: 300px;
  }

  :deep(.n-carousel) {
    height: 300px !important;
  }

  .order-status-section {
    position: relative;
    bottom: auto;
  }
}

@media (max-width: 480px) {
  .equipment-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .equipment-card {
    min-height: 340px;
  }

  .equipment-image {
    height: 180px;
  }

  .card-content {
    padding: 12px 14px;
    min-height: 120px;
  }
}
</style>
